from django.db.models import Sum, Count, F, Q, Func
from django.http import JsonResponse, HttpResponse
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from app01.models import ABSO_order
from datetime import datetime, timedelta
from app01.Baseview import BasedAPIView
from dateutil.rrule import rrule, DAILY


class DailyMetricsAPIView(BasedAPIView):
    def getHomeChatAll(self, request, format=None):
        page = int(request.GET.get("page", 1))  # 获取get请求传递的参数 page
        pagesize = int(request.GET.get("pagesize", 10))
        createTime = request.GET.getlist("createTime[]", [])

        query = Q()

        # 默认查询过去31天的数据
        default_start_date = timezone.now().date() - timedelta(days=7)
        default_end_date = timezone.now().date()
        # 如果提供了有效的开始和结束时间，则覆盖默认查询条件
        if len(createTime) == 2:
            start_date_str = createTime[0].strip()
            end_date_str = createTime[1].strip()
            if start_date_str and end_date_str:
                start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
                end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date()
                # 确保开始日期不超过结束日期
                # if start_date > end_date:
                #     raise ValueError("Start date cannot be after end date.")
                # # 检查日期范围是否超过31天
                # if (end_date - start_date).days > 31:
                #     raise ValueError("Date range cannot exceed 31 days.")
                query &= Q(createTime__range=(start_date, end_date + timedelta(days=1)))
        else:
            # 使用默认时间范围
            query &= Q(createTime__range=(default_start_date, default_end_date))

        start_page = page * pagesize - pagesize
        end_page = page * pagesize

        # 获取订单数据并按日期分组
        orders = ABSO_order.objects.filter(query).annotate(
            date=Func(F('createTime'), function='DATE')
        ).values('date').annotate(
            total_price=Sum('totalprice'),
            order_count=Count('id'),
            avg_price=F('total_price') / F('order_count')
        ).order_by('date')
        #
        # # 获取默认时间范围内的 totalPrice 总和
        # total_price_sum = ABSO_order.objects.filter(query).aggregate(total_price=Sum('totalprice'))['total_price']
        # # 获取默认时间范围内的订单数据并按 code 分组统计
        # order_counts = ABSO_order.objects.filter(query).count()
        # custom_price = round(total_price_sum / order_counts, 2)
        # #
        # # # 初始化返回数据
        # data = []
        # for order in orders:
        #     data_point = {
        #         'date': order['date'].strftime('%Y-%m-%d'),
        #         'datasets': {
        #             'order_count': order['order_count'],
        #             'total_price': float(order['total_price']) if order['total_price'] else 0,
        #             'avg_price': round(float(order['avg_price']) if order['avg_price'] else 0, 2)
        #         }
        #     }
        #     data.append(data_point)
        #
        # # for items in orders:
        # #     data.append({
        # #         'date': items['date'].strftime('%Y-%m-%d'),
        # #         'total_price': items['total_price'],
        # #         'order_count': items['order_count'],
        # #         'avg_price': round(items['avg_price'], 2)
        # #     })
        #
        # # dateDic = []
        # # datasets = {
        # #     'order_count': [],
        # #     'total_price': [],
        # #     'avg_price': []
        # # }
        # # for order in orders:
        # #     dateDic.append(order['date'].strftime('%Y-%m-%d'))
        # #     datasets['order_count'].append(order['order_count'])
        # #     datasets['total_price'].append(float(order['total_price']))
        # #     datasets['avg_price'].append(round(float(order['avg_price']), 2))
        # #
        # # res_data = {
        # #     'dateDic': dateDic,
        # #     'datasets': [
        # #         {
        # #             'label': '订单数',
        # #             'data': datasets['order_count']
        # #         },
        # #         {
        # #             'label': '订单总额',
        # #             'data': datasets['total_price']
        # #         },
        # #         {
        # #             'label': '客单价',
        # #             'data': datasets['avg_price']
        # #         }
        # #     ]
        # # }
        #
        # total = {
        #     'total': orders.count(),
        #     'total_price_sum': total_price_sum,
        #     'order_counts': order_counts,
        #     'custom_price': custom_price
        # }
        #
        # return super().success(total=total, data=data)

        delaute_dates = {dt.date(): {
            'total_price': None,
            'order_count': 0,
            'avg_price': None
        } for dt in rrule(DAILY, dtstart=start_date or default_start_date, until=end_date or default_end_date)}

        # 更新字典中的实际数据
        for entry in orders:
            delaute_dates[entry['date']] = {
                'total_price': float(entry['total_price']) if entry['total_price'] is not None else None,
                'order_count': entry['order_count'],
                'avg_price': round(float(entry['avg_price']), 2) if entry['avg_price'] is not None else None
            }

        # 将字典转换为有序列表，以保持日期顺序
        ordered_results = [
            {
                'date': dt.isoformat(),
                'datasets': delaute_dates[dt]
            }
            for dt in sorted(delaute_dates.keys())
        ]

        # 分页获取数据
        paginated_orders = ordered_results

        # 获取默认时间范围内的 totalPrice 总和和订单数量
        total_price_sum = ABSO_order.objects.filter(query).aggregate(total_price=Sum('totalprice'))[
                              'total_price'] or 0.0
        order_counts = ABSO_order.objects.filter(query).count()

        # 计算自定义价格，避免除以零
        custom_price = round(total_price_sum / order_counts, 2) if order_counts > 0 else 0.0

        # 返回JSON响应
        res_data = {
            'total': len(ordered_results),
            'total_price_sum': total_price_sum,
            'order_counts': order_counts,
            'custom_price': custom_price,
            'data': paginated_orders
        }

        return super().success(total=res_data['total'], data=res_data['data'])
